﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using BCEntity.WeChatComponent.WeChatAccessToken;
using Dapper;
using BCCommon;
namespace BCData.WeChatComponent.WeChatAccessToken
{
    /// <summary>
    /// 微信AccessToken数据处理
    /// </summary>
    public class WeChatAccessTokenData : IWeChatAccessTokenData
    {
        private readonly IDatabaseContext databaseContext;

        public WeChatAccessTokenData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        public WeChatAccessTokenEntity Get()
        {
            string sql = @"SELECT AccessToken,ExpiresIn,CreateTime,JsapiTicket FROM WeChatTokenRecord WHERE AccessTokenId=1;";
            return this.databaseContext.Slave.QueryEntity<WeChatAccessTokenEntity>(sql,CommandType.Text);
        }

        public WeChatAccessTokenEntity Update(WeChatAccessTokenEntity weChatAccessTokenEntity)
        {
            string sql = @"UPDATE WeChatTokenRecord SET
                               AccessToken=?AccessToken,
                               ExpiresIn=?ExpiresIn,
                               CreateTime=?CreateTime,
                                JsapiTicket=?JsapiTicket
                            WHERE AccessTokenId=1;
                            SELECT AccessToken,ExpiresIn,CreateTime FROM WeChatTokenRecord WHERE AccessTokenId=1;";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?AccessToken",weChatAccessTokenEntity.AccessToken,DbType.AnsiString,size:500);
            parameters.Add("?ExpiresIn", weChatAccessTokenEntity.ExpiresIn, DbType.Int32);
            parameters.Add("?CreateTime", weChatAccessTokenEntity.CreateTime, DbType.DateTime);
            parameters.Add("?JsapiTicket", weChatAccessTokenEntity.JsapiTicket, DbType.AnsiString, size: 255);
            return this.databaseContext.Master.QueryEntity<WeChatAccessTokenEntity>(sql,parameters, databaseContext.Transaction);
        }
    }
}
